import { Injectable } from '@nestjs/common';
import { CreateStudentDto } from './dto/create-student.dto';
import { UpdateStudentDto } from './dto/update-student.dto';
import { plainToInstance } from 'class-transformer';
import { Student } from './entities/student.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { PageStudentDto } from './dto/page-student.dto';
import { PageResult } from '../common/dto/common.page-result';

@Injectable()
export class StudentService {
  constructor(
    @InjectRepository(Student)
    private readonly studentRepository: Repository<Student>,
  ) {
  }

  async create(createStudentDto: CreateStudentDto) {
    const student = plainToInstance(Student, createStudentDto);
    await this.studentRepository.save(student);
  }

  findAll(): Promise<Student[]> {
    return this.studentRepository.find();
  }

  findOne(id: number): Promise<Student> {
    return this.studentRepository.findOne({ where: { id } });
  }

  async update(id: number, updateStudentDto: UpdateStudentDto) {
    await this.studentRepository.update(id, updateStudentDto);
  }

  async remove(id: number) {
    const student: Student = await this.studentRepository.findOne({
      where: { id },
    });
    if (student) {
      await this.studentRepository.remove(student);
    } else {
      throw new Error('删除学生失败');
    }
  }

  async page(pageStudentDto: PageStudentDto) {
    const query = this.studentRepository.createQueryBuilder('student');
    if (pageStudentDto.name) {
      query.andWhere('student.name like :name', {
        name: `%${pageStudentDto.name}%`,
      });
    }
    if (pageStudentDto.mobile) {
      query.andWhere('student.mobile like :mobile', {
        mobile: `%${pageStudentDto.mobile}%`,
      });
    }
    const [data, total] = await query
      .skip((pageStudentDto.page - 1) * pageStudentDto.size)
      .take(pageStudentDto.size)
      .getManyAndCount();

    return new PageResult(
      pageStudentDto.page,
      pageStudentDto.size,
      total,
      data,
    );
  }
}
